var showChat = false;
private var inputField = "";
private var display = true;
private var entries = ArrayList();
private var scrollPosition : Vector2;
private var GamePaused = true;

private var window = Rect(15, Screen.height/2, 200, 200);

class ChatEntry
{
	var sender = "";
	var text = "";	
	var mine = true;
}

function FocusControl ()
{
	// We can't select it immediately because the control might not have been drawn yet.
	// Thus it is not known to the system!
	yield;
	yield;
	yield;
	Screen.showCursor = true;
}

function OnGUI ()
{
	if(GamePaused)
		GUI.color = new Color(1,0.1,0.1,0.7);
	else
		GUI.color = new Color(1,0.1,0.1,1);
	
	window = GUI.Window (1, window, GlobalChatWindow, "Discussions");
	if(!GamePaused)
		GUI.FocusControl("Chat input field");
	else
		GUI.UnfocusWindow();
	FocusControl();
}

function GlobalChatWindow (id : int) {
	// Begin a scroll view. All rects are calculated automatically - 
    // it will use up any available screen space and make sure contents flow correctly.
    // This is kept small with the last two parameters to force scrollbars to appear.
	scrollPosition = GUILayout.BeginScrollView (scrollPosition);

	for (var entry : ChatEntry in entries)
	{
		//GUILayout.FlexibleSpace();
		GUILayout.Label(entry.text);
		GUILayout.Space(1);
	}
	// End the scrollview we began above.
    GUILayout.EndScrollView ();
	
	if (Event.current.type == EventType.keyDown && Event.current.character == "\n" && inputField.Length > 0)
	{
		var playerInfoObj = GameObject.FindWithTag ("PlayerInfo");
		var playerInfoComp = playerInfoObj.GetComponent("PlayerInfo");
		//@TODO: This should be dependent on who actually sent the message
		//var mine = entries.Count % 2 == 0;
		ApplyGlobalChatText(playerInfoComp.Pseudo+" : "+inputField, 1);
		networkView.RPC("ApplyGlobalChatText", RPCMode.Others, playerInfoComp.Pseudo+" : "+inputField, 0);
		inputField = "";
	}
	GUI.SetNextControlName("Chat input field");
	inputField = GUILayout.TextField(inputField);
	
	GUI.DragWindow();
}

@RPC
function ApplyGlobalChatText (str : String, mine : int)
{
	var entry = new ChatEntry();
	entry.text = str;
	if (mine == 1) entry.mine = true;
	else entry.mine = false;

	entries.Add(entry);
	
	if (entries.Count > 50)
		entries.RemoveAt(0);
		
	scrollPosition.y = 1000000;	
}

function Update(){
	if (Input.GetKeyDown(KeyCode.Tab))
	{
		for (var go : GameObject in FindObjectsOfType(GameObject))
		{
			go.SendMessage("TogglePause", 
			SendMessageOptions.DontRequireReceiver); 
		}
	}
}

function TogglePause()
{
	GamePaused = !GamePaused;
	Screen.showCursor = !Screen.showCursor;
	Screen.lockCursor = !Screen.lockCursor;
}